#!/bin/bash
#begin insmod; 

make_file=`find . -name "[Mm]akefile"`
module_name=`find . -name "*.c"`
module_name=${module_name##./}
module_name=`echo $module_name | cut -d "." -f 1`

if [ "$make_file" == "" ]
then
	echo "Makefile is non-exit，creating Makefile;" 
	echo "obj-m := $module_name.o" >> Makefile
	echo 'CURRENT_PATH := $(shell pwd)' >> Makefile
	echo 'LINUX_KERNEL := $(shell uname -r)' >> Makefile
	echo 'LINUX_KERNEL_PATH := /usr/src/kernels/$(LINUX_KERNEL)' >> Makefile
	echo 'all:' >> Makefile
	echo -e "\t"'make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules' >> Makefile
	echo "clean:" >> Makefile
	echo -e "\t"'make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) clean' >> Makefile
	echo "Makefile created success"
fi

make
if [ "$?" -ne 0 ] 
then
	echo "=======make error======="; 
	exit 1; 
fi

#uid_cur=`id -u`
#if [ "$uid_cur" -ne 0 ] 
#then
#	echo "当前用户不是root用户，开始切换root用户，请您输入密码:"
#	su root
#	if [ "$?" -ne 0 ] 
#	then
#		echo "您输入的密码错误，请重新运行程序"
#	fi
#fi

#开始准备插入模块;
dmesg -c; 
if [ "$?" -ne 0 ] 
then
	echo "=======dmesg error====="
	echo "请手动处理" 
	#exit 1
fi
clear; 
param_to_insert=`echo "$module_name.ko $@"`
sudo insmod $param_to_insert
if [ "$?" -ne 0 ] 
then
	echo "======insmod error====="
	exit 1
fi
dmesg; 
sudo rmmod "$module_name"
if [ "$?" -ne 0 ] 
then
	echo "======rmmod error====="; 
	exit 1; 
fi
